"""
    游戏界面模块
    视图层(Views)
"""
import tkinter
from bll import GameCore
from models import Direction
from config import *
import os


class GameConsoleView:
    def __init__(self,master):
        # 创建核心类对象
        self.__core = GameCore()
        self.root = master
        # 设置窗口标题
        self.root.title('2048_game')

    def start(self):
        """
            游戏开始
        """
        self.__core.generate_number()
        self.__core.generate_number()
        self.print_atlas()

    def print_atlas(self):
        """
            打印地图
        """
        self.map_labels = []
        # 初始化窗口
        for r in range(len(self.__core.atlas)): #r代表行
            row = [] #用来记录一行的label
            for c in range(len(self.__core.atlas[r])): #c代表列
                label = tkinter.Label(self.root,text='0',font = ('黑体',30,'bold'),bg = '#cdc1b4',width = 4,
                height=2)
                label.grid(row = r,column = c,padx=5,pady=5)
                row.append(label)
            self.map_labels.append(row)


    def move_atlas(self,event):
        """
            移动地图
        """
        if event.keysym == 'Up':
            self.__core.move(Direction.up)
            self.update()
        elif event.keysym == 'Down':
            self.__core.move(Direction.down)
            self.update()
        elif event.keysym == 'Left':
            self.__core.move(Direction.left)
            self.update()
        elif event.keysym == 'Right':
            self.__core.move(Direction.right)
            self.update()
        # 更新界面
        self.__update_ui()

    def run(self):
        """
            运行游戏
        """
        # 移动地图
        self.root.bind('<Key>',self.move_atlas)
        self.__update_ui()

    def update(self):
        """
            更新游戏
        """
        if self.__core.is_change:
            self.__core.generate_number()
            if self.__core.is_game_over():
                print("游戏结束")
                self.root.quit()
     

    def __update_ui(self):
        '''
            刷新界面函数
            根据计算出的地图数据,更新各个Label的设置
        '''
        for r in range(4):
            for c in range(4):
                number = self.__core.atlas[r][c]  # 设置数字
                label = self.map_labels[r][c]  # 选中Lable控件
                label['text'] = str(number) if number else ''
                label['bg'] = mapcolor[number][0]
                label['foreground'] = mapcolor[number][1]


